package ftp;

import com.jcraft.jsch.*;

import java.io.*;
import java.util.Properties;

/**
 * @author shenhan
 * @create 2020/2/10 17:11
 * @description
 */
public class SftpUtil {
    private static final int DEFAULT_PORT = 22;
    private static final int DEF_WAIT_SECONDS = 30;

    private static String username = "root";
    private static String host = "192.168.129.128";
    private static String password = "root";
    //源文件
    private static String sourcefile = "C:\\Users\\shenhan\\Desktop\\1581266780996_45043692.mp3";
    //放在服务器的目标位置
    private static String dstfilepath = "/root/";

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File(sourcefile);
        InputStream stream = new FileInputStream(file);
        run(stream);
    }

    public static void run(InputStream stream) {
        Session session = openSession(host, username, password);
        ChannelSftp openChannelSftp = openChannelSftp(session);
        try {
            openChannelSftp.put(stream, dstfilepath+"123.mp3", ChannelSftp.OVERWRITE);
            //删除文件可用如下方法，进入某文件所在的目录后删除该文件
            //openChannelSftp.cd(dstfilepath);
            //openChannelSftp.rm(sourcefile);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                closeChannel(openChannelSftp,session);
            } catch (Exception e) {
                System.out.println("client关闭失败");
            }
        }
    }

    /**
     * 创建服务器连接
     *
     * @param host
     *            主机
     * @param user
     *            用户
     * @param password
     *            密码
     * @return
     */
    private static Session openSession(String host, String user, String password) {
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, DEFAULT_PORT);
            noCheckHostKey(session);
            session.setPassword(password);
            // 这个设置很重要，必须要设置等待时长为大于等于2分钟
            session.connect(DEF_WAIT_SECONDS * 1000);
            if (!session.isConnected()) {
                throw new IOException("We can't connection to[" + host + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

    /**
     * 不作检查主机键值
     *
     * @param session
     */
    private static void noCheckHostKey(Session session) {
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
    }

    /**
     * 连接shell
     *
     * @param session
     *            session
     * @return {@link ChannelShell}
     */
    private static ChannelShell openChannelShell(Session session) {
        ChannelShell channel = null;
        try {
            channel = (ChannelShell) session.openChannel("shell");
            channel.setEnv("LANG", "en_US.UTF-8");
            channel.setAgentForwarding(false);
            channel.setPtySize(500, 500, 1000, 1000);
            channel.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (channel == null) {
            throw new IllegalArgumentException("The channle init was wrong");
        }
        return channel;
    }

    /**
     * 连接sftp
     *
     * @param session
     * @return {@link ChannelSftp}
     */
    private static ChannelSftp openChannelSftp(Session session) {
        ChannelSftp channel = null;
        try {
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channel;
    }

    private static void closeChannel(ChannelSftp openChannelSftp,Session session) throws Exception {
        if (openChannelSftp != null) {
            openChannelSftp.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        System.out.println("disconnected SFTP successfully!");
    }

}
